<?php
require('Base.php');
class AddUser extends Base
{
	/**
	 * 获取用户信息
	 * @param String $username 用户名
	 * @return Array
	 */
	public function getUserInfo(string $username)
	{
		// 预定义返回数据
		$res = $this->api_res;

		// 获取数据库连接
		$con = $this->connectDB();
		// 获取用户信息
		$db_prefix = $this->config['db']['prefix'];
		$data = [
			':username' => $username
		];
		$sql = "SELECT * FROM `{$db_prefix}user` WHERE `username`=:username AND `usable`=1 LIMIT 1;";
		$stm = $con->prepare($sql);
		$query = $stm->execute($data);
		if($query === false)
		{
			$res['err_msg'] = $stm->errorInfo();
			return $res;
		}
		$user_info = $stm->fetch(PDO::FETCH_ASSOC);
		if($user_info === false)
		{
			$res['err_msg'] = '用户不存在';
			return $res;
		}

		$res['status'] = 1;
		$res['data'] = $user_info;
		return $res;
	}


	/**
	 * 获取管理员ID
	 * @return Array
	 */
	public function getAdminId()
	{
		// 预定义返回数据
		$res = $this->api_res;

		// 获取数据库连接
		$con = $this->connectDB();
		// 获取管理员ID
		$db_prefix = $this->config['db']['prefix'];
		$sql = "SELECT MIN(`id`) AS `admin_id` FROM `{$db_prefix}user` WHERE `usable`=1;";
		$stm = $con->query($sql);
		if($stm === false)
		{
			$res['err_msg'] = $stm->errorInfo();
			return $res;
		}
		$admin_info = $stm->fetch(PDO::FETCH_ASSOC);
		if($admin_info === false)
		{
			$res['err_msg'] = '管理员不存在';
			return $res;
		}

		$res['status'] = 1;
		$res['data'] = $admin_info;
		return $res;
	}


	/**
	 * 用户名查重
	 * @param String $username 用户名
	 * @return Array
	 */
	public function checkUserExist(string $username)
	{
		// 预定义返回数据
		$res = $this->api_res;

		// 获取数据库连接
		$con = $this->connectDB();
		// 获取用户信息
		$db_prefix = $this->config['db']['prefix'];
		$data = [
			':username' => $username
		];
		$sql = "SELECT COUNT(`id`) AS `amount` FROM `{$db_prefix}user` WHERE `username`=:username AND `usable`=1;";
		$stm = $con->prepare($sql);
		$query = $stm->execute($data);
		if($query === false)
		{
			$res['err_msg'] = $stm->errorInfo();
			return $res;
		}
		$check_user_exist = $stm->fetch(PDO::FETCH_ASSOC);
		if($check_user_exist === false)
		{
			$res['err_msg'] = '读取用户表失败';
			return $res;
		}

		$res['status'] = 1;
		$res['data'] = [
			'exist' => (bool)$check_user_exist['amount']
		];
		return $res;
	}


	/**
	 * 新增用户
	 * @param Array $user_data 用户数据
	 *   $user_data['username'] 用户名
	 *   $user_data['pwd'] 密码
	 *   $user_data['salt'] 密码盐
	 * @return Array
	 */
	public function addUser(array $user_data)
	{
		// 预定义返回数据
		$res = $this->api_res;

		// 获取数据库连接
		$con = $this->connectDB();
		// 新增用户
		$db_prefix = $this->config['db']['prefix'];
		$data = [
			':username' => $user_data['username'],
			':pwd' => $user_data['pwd'],
			':salt' => $user_data['salt'],
			':create_time' => time()
		];
		$sql = "INSERT INTO `{$db_prefix}user` (`username`, `password`, `salt`, `create_time`) VALUES (:username, :pwd, :salt, :create_time);";
		$stm = $con->prepare($sql);
		$add_user = $stm->execute($data);
		if($add_user === false)
		{
			$res['err_msg'] = $add_user->errorInfo();
			return $res;
		}

		$res['status'] = 1;
		$res['data'] = [
			'user_id' => $con->lastInsertId()
		];
		return $res;
	}


}
/* ============================= CLASS FINISHED  ============================= */

	if( !($_POST) )
	{
		header('HTTP/1.1 403 Forbidden');
		die();
	}

	// 登录验证
	session_start();
	if(!isset($_SESSION['user']) || !$_SESSION['user'])
	{
		header('Location: ./login.html');
	}

	$AddUser = new AddUser();
	// 获取用户名、密码、确认密码
	$username = trim( strval($_POST['username']) );
	if(!$username)
	{
		$AddUser->error('用户名为空！');
	}
	$pwd = trim( strval($_POST['pwd']) );
	if(!$pwd)
	{
		$AddUser->error('密码为空！');
	}
	$repwd = trim( strval($_POST['repwd']) );
	if(!$repwd)
	{
		$AddUser->error('确认密码为空！');
	}
	// 比对两次输入的密码
	if($pwd != $repwd)
	{
		$AddUser->error('两次输入的密码不一致！');
	}

	// 获取当前登录的用户信息
	session_start();
	$current_user = $_SESSION['user'];
	$get_current_user_info = $AddUser->getUserInfo($current_user);
	if($get_current_user_info['status'] !== 1)
	{
		$err_msg = $get_current_user_info['err_msg'];
		$AddUser->error($err_msg);
	}
	$current_user_info = $get_current_user_info['data'];
	// 获取管理员ID（user表中的第一个用户）
	$get_admin_id = $AddUser->getAdminId();
	if($get_admin_id['status'] !== 1)
	{
		$err_msg = $get_admin_id['err_msg'];
		$AddUser->error($err_msg);
	}
	$admin_id = $get_admin_id['data']['admin_id'];
	// 管理员权限验证
	if($current_user_info['id'] != $admin_id)
	{
		$AddUser->error('仅管理员有权添加用户');
	}

	// 用户名查重
	$check_user_exist = $AddUser->checkUserExist($username);
	if($check_user_exist['status'] !== 1)
	{
		$err_msg = $check_user_exist['err_msg'];
		$AddUser->error($err_msg);
	}
	if($check_user_exist['data']['exist'] === true)
	{
		$AddUser->error('用户名已存在！');
	}

	// 计算密码盐
	$salt = $AddUser->makeSalt($pwd);
	// 计算密文密码
	$true_pwd = $AddUser->getCryptedPassword($pwd, $salt);
	// 添加用户
	$data_add_user = [
		'username' => $username,
		'pwd' => $true_pwd,
		'salt' => $salt
	];
	$add_user = $AddUser->addUser($data_add_user);
	if($add_user['status'] !== 1)
	{
		$err_msg = $check_user_exist['err_msg'];
		$AddUser->error($err_msg);
	}

	header('Location: ./index.php');

?>
